package com.mg.jsfapp.pattern.observer.impl;

import java.util.ArrayList;
import java.util.List;

import com.mg.jsfapp.pattern.observer.IObserver;
import com.mg.jsfapp.pattern.observer.ISubject;

public class WheatherReader implements ISubject {
   
   private double temperatore; // celsius degree
   private double windSpeed;   // km/h
   private double humidity;    // %
   

   private List<IObserver> observers = new ArrayList<IObserver>(3);
   private final Object MUTEX = new Object();

   @Override
   public void register(IObserver obj) {
      if (obj == null) {
         throw new NullPointerException("Null Observer");
      }
      synchronized (MUTEX) {
         if (!observers.contains(obj)) {
            observers.add(obj);
         }
      }
   }

   @Override
   public void unregister(IObserver obj) {
      synchronized (MUTEX) {
         observers.remove(obj);
      }
   }

   @Override
   public void notifyObservers() {
      synchronized (MUTEX) {
         for (IObserver obj : observers) {
            obj.update();
        }
      }
   }

   @Override
   public Object getUpdate(IObserver obj) {
      if (obj instanceof HumidityObserver) {
         return humidity;
      } else if (obj instanceof WindObserver) {
         return windSpeed;
      } else if (obj instanceof TemperatureObserver) {
         return temperatore;
      }
      return null;
   }
   
   public void readWheather() {
      this.temperatore = Math.random()*200;
      this.windSpeed = Math.random()*300;
      this.humidity = Math.random()*100;
      notifyObservers();
   }

}
